package com.qdxht.dispenser.utils.image;


import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;

import com.facebook.binaryresource.FileBinaryResource;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

import java.io.File;


public class FrescoImageLoader {
    /**
     * 从网络获取图片显示
     *
     * @param url       图片URL
     * @param imageView 要显示的view
     */
    public static void displayFromHttp(String url, SimpleDraweeView imageView) {
//        if (!TextUtils.isEmpty(url)){
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setAutoPlayAnimations(true)//自动播放动画
                .setUri(TextUtils.isEmpty(url) ? null : Uri.parse(url))//路径
                .build();
        imageView.setController(draweeController);
//        }
    }

    /**
     * display image from sd card.
     *
     * @param path      path of the image.
     * @param imageView the imageview to show image.
     */
    public static void displayFromSDCard(String path, SimpleDraweeView imageView) {
//        if (!TextUtils.isEmpty(path)){
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setAutoPlayAnimations(true)//自动播放动画
                .setUri(TextUtils.isEmpty(path) ? null : Uri.parse("file://" + path))//路径
                .build();
        imageView.setController(draweeController);
//        }

//        imageView.setImageURI(Uri.parse("file://" + path));
    }

    public static void displayFromUri(Uri uri, SimpleDraweeView imageView) {
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setAutoPlayAnimations(true)//自动播放动画
                .setUri(uri)//路径
                .build();
        imageView.setController(draweeController);
    }

    /**
     * display image from drawable.
     *
     * @param imageId   the id of the image.
     * @param imageView the imageview to show image.
     */
    public static void displayFromDrawable(int imageId, SimpleDraweeView imageView) {
//        if (imageId!=0){
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setAutoPlayAnimations(true)//自动播放动画
                .setUri(imageId == 0 ? null : Uri.parse("res:///" + imageId))//路径
                .build();
        imageView.setController(draweeController);
//        }

//        imageView.setImageURI(Uri.parse("res:///" + imageId));
    }

    //    /**
//     * display image from assets
//     * @param imageName name of the image, for example 1.png.
//     * @param imageView the imageview to show image.
//     */
    public static void dispalyFromAssets(String imageName, SimpleDraweeView imageView) {
        DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                .setAutoPlayAnimations(true)//自动播放动画
                .setUri(TextUtils.isEmpty(imageName) ? null : Uri.parse("asset:///" + imageName))//路径
                .build();
        imageView.setController(draweeController);
    }
//
//    /**
//     * display image from content provider
//     * @param uri       uri of the image
//     * @param imageView the imageview to show image.
//     */
//    public static void displayFromContent(String uri, SimpleDraweeView imageView) {
//        imageView.setImageURI(Uri.parse("content://" + uri));
//    }

//    /**
//     * 将指定URL的网络图片保存到指定路径文件中
//     * @param context
//     * @param picUrl 图片URL
//     * @param path 保存路径
//     * @throws Exception
//     */
//    public static void saveImageToDisk(final Context context, String picUrl, final String path) throws Exception {
//        File file = getCachedImageOnDisk(picUrl,context);
//        if (file != null) {
//            FileUtil.write2SDFromInput(path, new FileInputStream(file));
//        } else {
//            //从缓存中取图片保存到本地
//            ImageRequest imageRequest = ImageRequestBuilder
//                    .newBuilderWithSource(Uri.parse(picUrl))
//                    .setProgressiveRenderingEnabled(true)
//                    .build();
//
//            ImagePipeline imagePipeline = Fresco.getImagePipeline();
//            DataSource<CloseableReference<CloseableImage>>
//                    dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
//
//            dataSource.subscribe(new BaseBitmapDataSubscriber() {
//                @Override
//                public void onNewResultImpl(Bitmap bitmap) {
//                    if (bitmap == null) {
//                        ToastUtil.showShortToast(context, "保存图片失败啦,无法下载图片");
//                    } else {
//                        ImageUtil.saveBitmapToSDcard(path, bitmap, 100);
//                    }
//                }
//
//                @Override
//                public void onFailureImpl(DataSource dataSource) {
//                }
//            }, CallerThreadExecutor.getInstance());
//        }
//    }

//    public static void displayFromHttpAndBlur(Context context, final SimpleDraweeView view, String picUrl, final int radius) throws Exception {
//        ImageDecodeOptions decodeOptions = ImageDecodeOptions.newBuilder()
////                .setBackgroundColor(Color.GRAY)
//                .build();
//        ImageRequest imageRequest = ImageRequestBuilder
//                .newBuilderWithSource(Uri.parse(picUrl))
//                .setImageDecodeOptions(decodeOptions)
//                .setAutoRotateEnabled(true)
//                .setLowestPermittedRequestLevel(ImageRequest.RequestLevel.FULL_FETCH)
//                .setProgressiveRenderingEnabled(true)//渐进渲染
////                .setResizeOptions(new ResizeOptions(300, 300))
//                .build();
//        ImagePipeline imagePipeline = Fresco.getImagePipeline();
//        DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
//
//        dataSource.subscribe(new BaseBitmapDataSubscriber() {
//            @Override
//            protected void onNewResultImpl(Bitmap bitmap) {
//                //获取图片的bitmap
//                if(bitmap!=null){
//                    view.setImageBitmap(ImageUtil.doBlur(bitmap,radius));
//                }
//            }
//
//            @Override
//            protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
//
//            }
//        }, UiThreadImmediateExecutorService.getInstance());
//    }

    //    public static File getCachedImageOnDisk(String picUrl, Context context) {
//        CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(Uri.parse(picUrl)),context);
//        File localFile = null;
//        if (cacheKey != null) {
//            if (ImagePipelineFactory.getInstance().getMainDiskStorageCache().hasKey(cacheKey)) {
//                BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey);
//                localFile = ((FileBinaryResource) resource).getFile();
//            } else if (ImagePipelineFactory.getInstance().getSmallImageDiskStorageCache().hasKey(cacheKey)) {
//                BinaryResource resource = ImagePipelineFactory.getInstance().getSmallImageDiskStorageCache().getResource(cacheKey);
//                localFile = ((FileBinaryResource) resource).getFile();
//            }
//        }
//        return localFile;
//    }
    public static File getCachedImageOnDisk(String picUrl) {
        FileBinaryResource resource = (FileBinaryResource) Fresco.getImagePipelineFactory().getMainFileCache().getResource(new SimpleCacheKey(picUrl));
        File file2 = resource.getFile();

        return file2;
    }

    /**
     * 删除某张网络图片的缓存
     *
     * @param url 图片URL
     */
    public static void clearImageCache(String url) {
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
//        imagePipeline.evictFromMemoryCache(uri);
//        imagePipeline.evictFromDiskCache(uri);

//        combines above two lines
        imagePipeline.evictFromCache(Uri.parse(url));
    }

    /**
     * 清除Fresco缓存的所有图片
     */
    public static void clearAllCache() {
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        imagePipeline.clearCaches();
    }

    /**
     * 高斯模糊后显示
     *
     * @param url
     * @param draweeView
     * @param context
     * @param radius     高斯模糊的半径, 每一个像素都取周边(多少个)像素的平均值
     */
    public static void loadUrlInBlur(String url, SimpleDraweeView draweeView,
                                     Context context, int radius) {
        if (TextUtils.isEmpty(url)) {
            FrescoImageLoader.displayFromHttp(url, draweeView);
            return;
        }
        loadUrl(Uri.parse(url), draweeView, new BlurPostprocessor(context, radius, 1), null);
    }

    //    int width, int height,
    private static void loadUrl(Uri uri, SimpleDraweeView draweeView, BasePostprocessor processor,
                                BaseControllerListener listener) {
        ImageRequest request =
                ImageRequestBuilder.newBuilderWithSource(uri)
                        .setPostprocessor(processor)
//                        .setResizeOptions(new ResizeOptions(width,height))
                        //缩放,在解码前修改内存中的图片大小, 配合Downsampling可以处理所有图片,否则只能处理jpg,
                        // 开启Downsampling:在初始化时设置.setDownsampleEnabled(true)
                        .setProgressiveRenderingEnabled(true)//支持图片渐进式加载
                        .setAutoRotateEnabled(true) //如果图片是侧着,可以自动旋转
                        .build();

        PipelineDraweeController controller =
                (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                        .setImageRequest(request)
                        .setControllerListener(listener)
                        .setOldController(draweeView.getController())
                        .setAutoPlayAnimations(true) //自动播放gif动画
                        .build();

        draweeView.setController(controller);
    }

}
